<?php
/**
 * Created by PhpStorm.
 * User: fantaixi
 * Date: 2018/9/19
 * Time: 10:50
 */

namespace app\admin\controller;


use app\common\attr;
use think\Db;
use PHPExcel_IOFactory;

class Games extends Base
{
    public $table = 'games';
    public function index()
    {
        $type = input('type');
        $keyword = input('keyword');
        $where = null;
        if($type){
            $where['type'] = ['eq',$type];
        }
        if($keyword){
            $where['name'] = ['like','%'.$keyword.'%'];
        }
        if(!$where){
            $where = '1=1';
        }
        $data = Db::name($this->table)->where($where)->order('id desc')->paginate();
        $page = $data->render();
        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('type',$type);
        $this->assign('keyword',$keyword);
        return $this->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            return $this->save();
        }
        $this->assign('data',1);
        $this->assign('title','新增');
        $this->assign('url',url('add'));
        return $this->fetch('info');
    }

    public function update()
    {
        $id = input('id/d');
        $data = Db::name($this->table)->where('id',$id)->find();
        if(!$data){
            $this->error('不存在');
        }
        if(request()->isPost()){
            return $this->save();
        }
        $data['start'] = $data['start']?date('Y-m-d',$data['start']):'';
        $data['end'] = $data['end']?date('Y-m-d',$data['end']):'';
        $data['deadline'] = $data['deadline']?date('Y-m-d',$data['deadline']):'';
        $this->assign('data',json_encode($data));
        $this->assign('title','编辑');
        $this->assign('url',url('update'));
        return $this->fetch('info');
    }

    public function save()
    {
        $id = input('id/d');
        $data = [
            'name'=>input('name'),
            'type'=>input('type'),
            'img'=>input('img'),
            'price'=>round(input('price'),2),
            'info'=>input('info'),
            'display'=>input('display'),
            'start'=>strtotime(input('start')),
            'end'=>strtotime(input('end')),
            'deadline'=>strtotime(input('deadline'))+24*3600-1,
            'sex1'=>input('sex1/d'),
            'sex2'=>input('sex2/d'),
            'age1'=>input('age1/d'),
            'age2'=>input('age2/d'),
            'player_number'=>input('player_number/d'),
            'modtime'=>time(),
        ];
        if($id){
            $a = Db::name($this->table)->where('id',$id)->update($data);
        }else{
            $data['addtime'] = time();
            $a = Db::name($this->table)->insert($data);
        }
        if($a){
            echo api_return(1,'保存成功');
        }else{
            echo api_return(0,'保存失败');
        }
        return;
    }

    /**
     * 参赛队员
     */
    public function player()
    {
        $id = input('id/d');
        $game = $this->getGames($id);
        $data = $this->getPlayers($game);
        $count = $data?count($data):0;
        $this->assign('data',$data);
        $this->assign('count',$count);
        $this->assign('game',$game);
        return $this->fetch();
    }

    /**
     * 比赛结果
     */
    public function results()
    {
        $id = input('id/d');
        $game = $this->getGames($id);

        switch ($game['type'])
        {
            //单打/双打
            case 1:
            case 2:
            $field = 'a.*,b.nickname as player11_nickname,b.name as player11_name,
        c.nickname as player12_nickname,c.name as player12_name,
        d.nickname as player21_nickname,d.name as player21_name,
        e.nickname as player22_nickname,e.name as player22_name,f.name as attr_name';
            $data = Db::name('result')
                ->alias('a')
                ->join('games_player m','a.player1_id=m.id')
                ->join('games_player n','a.player2_id=n.id')
                ->join('member b','b.id=m.member1_id','left')
                ->join('member c','c.id=m.member2_id','left')
                ->join('member d','d.id=n.member1_id','left')
                ->join('member e','e.id=n.member2_id','left')
                ->join('attr f','f.id=a.attr_id')
                ->where('a.games_id',$id)
                ->field($field)
                ->order('a.id desc')
                ->paginate();
                break;
            //团队
            case 3:
                $data = Db::name('result')
                    ->alias('a')
                    ->join('club b','b.id=a.club1_id')
                    ->join('club c','c.id=a.club2_id')
                    ->join('attr d','d.id=a.attr_id')
                    ->where('a.games_id',$id)
                    ->field('a.*,b.name as club1_name,c.name as club2_name,d.name as attr_name')
                    ->order('a.id desc')
                    ->paginate();
        }



        $page = $data->render();
        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('game',$game);
        return $this->fetch();
    }

    private function getGames($id)
    {
        $data = Db::name($this->table)->where('id',$id)->find();
        if($data)
            return $data;
        return $this->error('不存在');
    }

    public function add_results()
    {
        $id = input('games_id');
        $game = $this->getGames($id);
        if(request()->isPost()){
            return $this->save_result();
        }

        $this->assign('players',json_encode($this->getPlayers($game)));
        $this->assign('type',$game['type']);
        $this->assign('data',1);
        $this->assign('title','新增比赛结果');
        $this->assign('games_id',$id);
        $this->assign('url',url('add_results'));
        $this->assign('result_type',json_encode($this->get_result_type()));
        return $this->fetch('results_info');
    }

    public function get_result_type()
    {
        return attr::get_list('result_type');
    }

    public function update_results()
    {
        $id= input('id/d');
        $data = Db::name('result')->where('id',$id)->find();
        if(!$data){
            $this->error('不存在');
        }
        if(request()->isPost()){
            return $this->save_result();
        }

        $game = $this->getGames($data['games_id']);
        $this->assign('players',json_encode($this->getPlayers($game)));
        $this->assign('type',$game['type']);
        $this->assign('data',json_encode($data));
        $this->assign('title','编辑比赛结果');
        $this->assign('games_id',$data['games_id']);
        $this->assign('url',url('update_results'));
        $this->assign('result_type',json_encode($this->get_result_type()));

        return $this->fetch('results_info');
    }

    public function ajax_update()
    {
        $type = input('type');
        $field = input('field');
        $data[$field] = input('value/d');
        $id = input('id/d');
        $data['modtime'] = time();
        if($type==3){
            $a = Db::name('games_club')->where('id',$id)->update($data);
        }else{
            $a = Db::name('games_player')->where('id',$id)->update($data);
        }
        if($a){
            echo api_return(1,'保存成功');
        }else{
            echo api_return(0,'保存失败');
        }
    }

    private function getPlayers($game)
    {
        if($game['type']==3){
            $data = Db::name('games_club')
                ->alias('a')
                ->join('club b','b.id=club_id')
                ->where('games_id',$game['id'])
                ->field('a.*,b.name as club_name')
                ->order('a.id asc')
                ->select();
        }else{
            $data = Db::name('games_player')
                ->alias('a')
                ->join('member b','b.id=member1_id')
                ->join('member c','c.id=member2_id','left')
                ->where('games_id',$game['id'])
                ->field('a.*,b.nickname as member1_nickname,b.name as member1_name,b.sex as member1_sex,b.birth as member1_birth,
                b.tel as member1_tel,c.nickname as member2_nickname,c.name as member2_name,c.sex as member2_sex,
                c.birth as member2_birth,c.tel as member2_tel')
                ->order('a.id asc')
                ->select();
        }
        return $data;
    }

    public function save_result()
    {
        $id = input('id/d');
        $data = [
            'attr_id'=>input('attr_id/d'),
            'score1'=>input('score1'),
            'score2'=>input('score2'),
            'club1_id'=>input('club1_id'),
            'club2_id'=>input('club2_id'),
            'player1_id'=>input('player1_id'),
            'player2_id'=>input('player2_id'),
            'sort'=>input('sort/d'),
            'modtime'=>time(),
        ];
        if($id){
            $a = Db::name('result')->where('id',$id)->update($data);
        }else{
            $data['addtime'] = time();
            $data['games_id'] = input('games_id/d');
            $a = Db::name('result')->insert($data);
        }
        if($a){
            echo api_return(1,'保存成功');
        }else{
            echo api_return(0,'保存失败');
        }
        return;
    }

    /**
     * 删除
     */
    public function ajax_del_results()
    {
        $id = input('id');
        $a = Db::name('result')->where('id',$id)->delete();
        if($a){
            echo api_return(1,'删除成功');
        }else{
            echo api_return(0,'删除失败');
        }
    }

    public function club_player()
    {
        $id = input('id');
        $gameClub = Db::name('games_club')
            ->alias('a')
            ->join('club b','b.id=a.club_id')
            ->where('a.id',$id)
            ->field('a.*,b.name')
            ->find();
        if(!$gameClub)
            $this->error('不存在');

        $data = Db::name('games_player')
            ->alias('a')
            ->join('member b','b.id=a.member1_id')
            ->where('games_id',$gameClub['games_id'])
            ->where('club_id',$gameClub['club_id'])
            ->field('a.*,b.nickname,b.name,b.sex,b.birth')
            ->order('a.id desc')
            ->select();
        $count = $data?count($data):0;
        $this->assign('data',$data);
        $this->assign('count',$count);
        $this->assign('gameClub',$gameClub);
        return $this->fetch();
    }

    /**
     * 下载参赛人员名单
     */
    public function download()
    {
        $id = input('id');
        $game = $this->getGames($id);
        if($game['type']!=3){
            $data = $this->getPlayers($game);
        }else{
            $data = $this->getClubPlayers($game);
        }


        $excel_title = $game['name'].'参赛人员/俱乐部名单';
        $sheet_title = $game['name'];
        $PHPExcel = new \PHPExcel(); //实例化PHPExcel类，类似于在桌面上新建一个Excel表格
        $PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
        $PHPSheet->setTitle($sheet_title); //给当前活动sheet设置名称

        //给当前活动sheet填充数据，数据填充是按顺序一行一行填充的，假如想给A1留空，可以直接setCellValue('A1','');
        $PHPSheet->setCellValue('A1','ID')
            ->setCellValue('B1','俱乐部名称')
            ->setCellValue('C1','队员1姓名')
            ->setCellValue('D1','队员1性别')
            ->setCellValue('E1','队员1出生年月')
            ->setCellValue('F1','队员1年龄')
            ->setCellValue('G1','队员1电话')
            ->setCellValue('H1','队员2姓名')
            ->setCellValue('I1','队员2性别')
            ->setCellValue('J1','队员2出生年月')
            ->setCellValue('K1','队员2年龄')
            ->setCellValue('L1','队员2电话')
            ->setCellValue('M1','报名时间');

        if($data){
            foreach ($data as $key=>$value)
            {
                $PHPSheet->setCellValue('A'.($key+2),$key+1)
                    ->setCellValue('B'.($key+2),$value['club_name']??'')
                    ->setCellValue('C'.($key+2),$value['member1_name'])
                    ->setCellValue('D'.($key+2),$value['member1_sex']==1?'男':'女')
                    ->setCellValue('E'.($key+2),date('Y-m-d',$value['member1_birth']))
                    ->setCellValue('F'.($key+2),caleAge($value['member1_birth']))
                    ->setCellValue('G'.($key+2),$value['member1_tel'])
                    ->setCellValue('H'.($key+2),$value['member2_name']??'')
                    ->setCellValue('I'.($key+2),isset($value['member2_sex'])?($value['member2_sex']==1?'男':'女'):'')
                    ->setCellValue('J'.($key+2),isset($value['member2_birth'])?date('Y-m-d',$value['member2_birth']):'')
                    ->setCellValue('K'.($key+2),isset($value['member2_birth'])?caleAge($value['member2_birth']):'')
                    ->setCellValue('L'.($key+2),isset($value['member2_tel'])?$value['member2_tel']:'')
                    ->setCellValue('M'.($key+2),date('Y-m-d H:i',$value['addtime']));
            }
        }

        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件，'Excel2007'表示生成2007版本的xlsx，'Excel5'表示生成2003版本Excel文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        header('Content-Disposition: attachment;filename="'.$excel_title.'.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");
    }

    private function getClubPlayers($game)
    {
        $data = Db::name('games_player')
            ->alias('a')
            ->join('club b','b.id=a.club_id')
            ->join('member c','c.id=a.member1_id')
            ->where('a.games_id',$game['id'])
            ->field('a.*,b.name as club_name,c.name as member1_name,c.sex as member1_sex,c.tel as member1_tel,c.birth as member1_birth')
            ->order('a.id asc')
            ->select();
        return $data;
    }

//    private function getPlayer($game)
//    {
//        switch ($game['type'])
//        {
//            //单打/双打
//            case 1:
//            case 2:
//                $field = 'a.*,b.nickname as member1_nickname,b.name as member1_name,
//        c.nickname as member1_nickname,c.name as member2_name';
//                $data = Db::name('games_player')
//                    ->alias('a')
//                    ->join('member b','b.id=a.member1_id','left')
//                    ->join('member c','c.id=a.member2_id','left')
//                    ->where('a.games_id',$game['id'])
//                    ->field($field)
//                    ->order('a.id desc')
//                    ->select();
//                break;
//            //团队
//            case 3:
//                $data = Db::name('games_club')
//                    ->alias('a')
//                    ->join('club b','b.id=a.club_id')
//                    ->where('a.games_id',$game['id'])
//                    ->field('a.*,b.name as club_name')
//                    ->order('a.id desc')
//                    ->select();
//        }
//        return $data;
//    }
}